Using useImperativeHandle to Access Child Component Functionality
I’ve come across `useImparativeHandle` and `forwardRef`s here and there, but never thought much about them. Recently, I stumbled across them again and decided to look into them a bit. As usual, I could have definitely used these in the design of controlled components in the past to simplify the passing of state and functionality between child and parent. Jeez.
`useImpartiveHandle` allows us to define functions to be exposed through a ref, which parent components can use.
```javascript
import React from 'react';
import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
const SomeComponent = forwardRef((props, ref) => {
useImperativeHandle(ref, () => {
\ return {
\ functionToCall: () => console.log("Calling a child component's function")
\ };
}, []);
return
SomeComponent
;});
export function App() {
const childComponentRef = useRef();
useEffect(() => {
\ if (childComponentRef.current) {
\ childComponentRef.current.functionToCall();
\ }
}, []);
return (
\
);
}
// Log to console
console.log('Hello console')
```